package com.wang.lwm.exception;

import com.wang.lwm.enums.YmccSystemError;
import com.wang.lwm.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/*
    全局异常处理
 */
@Slf4j
@RestControllerAdvice //  当目标controller发生异常的时候，被GlobalExceptionHandler 拦截
public class GlobalExceptionHandler {

    /*
        pethome抛出的异常类型：
            BusinessException：需要我们主动抛出错误的时候
            其他异常：被动出错----Exception

     */

    //要拦截的错误类型
    @ExceptionHandler(Exception.class)
    public JSONResult globalException(HttpServletResponse response, Exception ex){

        ex.printStackTrace();
        log.info("Exception...");
        log.info("错误代码："  + response.getStatus());


        return JSONResult.error(YmccSystemError.DB_SERVICE_ERROR);
    }

    //要拦截的错误类型
    @ExceptionHandler(GlobalException.class)
    public JSONResult businessException(HttpServletResponse response, GlobalException ex){

        ex.printStackTrace();
        log.info("GlobalExceptionHandler...");
        log.info("错误代码："  + response.getStatus());


        return JSONResult.error(ex.getMessage(),"-2");
    }

    //要拦截的错误类型
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult jsr303Exception(HttpServletResponse response, MethodArgumentNotValidException ex){

        ex.printStackTrace();
        log.info("MethodArgumentTypeMismatchException...");
        log.info("错误代码："  + response.getStatus());
        StringBuffer sb = new StringBuffer("数据格式有误：");
        //所有错误信息
        List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
        allErrors.forEach(ma -> sb.append(ma.getDefaultMessage()+";"));
        return JSONResult.error(sb.toString(),"20010");
    }

}
